/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-10-10 10:30:00
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-10 10:30:00
 * @FilePath: \work-tool\my-dev-project\src\views\order\aggregate.tsx
 * @Description: 订单聚合统计页面
 */
import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Select, Statistic, Tooltip, Space } from 'antd';
import {
  BarChart, Bar, LineChart, Line, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip as RechartsTooltip, Legend,
  ResponsiveContainer
} from 'recharts';
import {
  ArrowUpOutlined, ArrowDownOutlined, DollarOutlined,
  ShoppingCartOutlined, UserOutlined, ReloadOutlined
} from '@ant-design/icons';

// const { RangePicker } = DatePicker;
const { Option } = Select;

// 模拟订单聚合数据
const mockOrderAggregateData = {
  // 销售额统计（按日期）
  salesByDate: [
    { date: '09-01', sales: 12990, orders: 15, customers: 12 },
    { date: '09-02', sales: 18560, orders: 22, customers: 18 },
    { date: '09-03', sales: 15320, orders: 18, customers: 16 },
    { date: '09-04', sales: 22140, orders: 25, customers: 20 },
    { date: '09-05', sales: 19870, orders: 21, customers: 19 },
    { date: '09-06', sales: 24510, orders: 28, customers: 23 },
    { date: '09-07', sales: 21350, orders: 24, customers: 21 },
  ],

  // 订单状态分布
  orderStatusDistribution: [
    { name: '待支付', value: 25, color: '#ff9800' },
    { name: '已支付', value: 42, color: '#2196f3' },
    { name: '处理中', value: 18, color: '#9c27b0' },
    { name: '已发货', value: 65, color: '#4caf50' },
    { name: '已完成', value: 125, color: '#00bcd4' },
    { name: '已取消', value: 15, color: '#f44336' },
    { name: '已退货', value: 10, color: '#e91e63' },
  ],

  // 支付方式分布
  paymentMethodDistribution: [
    { name: '微信支付', value: 120, color: '#07c160' },
    { name: '支付宝', value: 95, color: '#1677ff' },
    { name: '信用卡', value: 45, color: '#722ed1' },
    { name: '现金', value: 20, color: '#fa8c16' },
  ],

  // 客户地域分布
  customerRegionDistribution: [
    { name: '华东', value: 85 },
    { name: '华南', value: 62 },
    { name: '华北', value: 78 },
    { name: '西南', value: 45 },
    { name: '西北', value: 32 },
    { name: '东北', value: 38 },
  ],

  // 本周销售趋势
  weeklyTrend: [
    { day: '周一', sales: 12990, orders: 15 },
    { day: '周二', sales: 18560, orders: 22 },
    { day: '周三', sales: 15320, orders: 18 },
    { day: '周四', sales: 22140, orders: 25 },
    { day: '周五', sales: 19870, orders: 21 },
    { day: '周六', sales: 24510, orders: 28 },
    { day: '周日', sales: 21350, orders: 24 },
  ],

  // 关键指标
  keyMetrics: {
    totalSales: 134740,
    totalOrders: 153,
    totalCustomers: 129,
    avgOrderValue: 880.65,
    growthRate: 15.6,
  }
};

// 颜色配置
const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#a358ff', '#ff5858', '#588cff'];

const OrderAggregate: React.FC = () => {
  const dateRange: [string, string] = ['2025-09-01', '2025-09-07'];
  const [timeRange, setTimeRange] = useState<string>('week');
  const [chartData, setChartData] = useState(mockOrderAggregateData);
  const [loading, setLoading] = useState<boolean>(false);

  // 处理时间范围选择
  // const handleDateRangeChange = (_dates: [Date | null, Date | null], dateStrings: string[]) => {
  //   if (dateStrings && dateStrings.length === 2) {
  //     setDateRange([dateStrings[0], dateStrings[1]]);
  //     // 在实际项目中，这里会根据选择的日期范围重新请求数据
  //     fetchAggregateData(dateStrings[0], dateStrings[1], timeRange);
  //   }
  // };

  // 模拟获取聚合数据
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const fetchAggregateData = (_startDate: string, _endDate: string, _timeRange: string) => {
    setLoading(true);
    // 模拟网络请求延迟
    setTimeout(() => {
      // 这里可以根据传入的参数动态生成或过滤数据
      setChartData(mockOrderAggregateData);
      setLoading(false);
    }, 800);
  };
  // 处理时间维度选择
  const handleTimeRangeChange = (value: string) => {
    setTimeRange(value);
    // 在实际项目中，这里会根据选择的时间维度重新请求数据
    fetchAggregateData(dateRange[0], dateRange[1], value);
  };
  // 刷新数据
  const refreshData = () => {
    fetchAggregateData(dateRange[0], dateRange[1], timeRange);
  };

  // 组件加载时初始化数据
  useEffect(() => {
    fetchAggregateData(dateRange[0], dateRange[1], timeRange);
  }, []);



  return (
    <div style={{ padding: 24 }}>
      <Card
        title="订单聚合统计"
        extra={
          <Space>
            {/* <RangePicker 
              value={
                dateRange.length === 2 && dateRange.every(date => dayjs(date).isValid()) 
                  ? dateRange.map(date => dayjs(date)) 
                  : [null, null]
              }
              onChange={handleDateRangeChange}
            /> */}
            <Select
              value={timeRange}
              style={{ width: 120 }}
              onChange={handleTimeRangeChange}
            >
              <Option value="day">按日</Option>
              <Option value="week">按周</Option>
              <Option value="month">按月</Option>
              <Option value="quarter">按季</Option>
            </Select>
            <Tooltip title="刷新数据">
              <button
                onClick={refreshData}
                disabled={loading}
                style={{
                  border: 'none',
                  background: 'none',
                  cursor: loading ? 'not-allowed' : 'pointer',
                  color: loading ? '#d9d9d9' : '#1890ff'
                }}
              >
                <ReloadOutlined spin={loading} />
              </button>
            </Tooltip>
          </Space>
        }
      >
        {/* 关键指标卡片 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} md={8} lg={6}>
            <Card bordered={false}>
              <Statistic
                title="总销售额"
                value={chartData.keyMetrics.totalSales}
                precision={2}
                valueStyle={{ color: '#3f8600' }}
                prefix={<DollarOutlined />}
                suffix="元"
                formatter={(value: number) => `¥${(Number(value) / 10000).toFixed(2)}万`}
              />
              <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', fontSize: 12, color: '#3f8600' }}>
                <ArrowUpOutlined size={12} style={{ marginRight: 4 }} />
                <span>较上期增长 {chartData.keyMetrics.growthRate}%</span>
              </div>
            </Card>
          </Col>

          <Col xs={24} sm={12} md={8} lg={6}>
            <Card bordered={false}>
              <Statistic
                title="总订单数"
                value={chartData.keyMetrics.totalOrders}
                valueStyle={{ color: '#1890ff' }}
                prefix={<ShoppingCartOutlined />}
              />
              <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', fontSize: 12, color: '#1890ff' }}>
                <ArrowUpOutlined size={12} style={{ marginRight: 4 }} />
                <span>较上期增长 12.3%</span>
              </div>
            </Card>
          </Col>

          <Col xs={24} sm={12} md={8} lg={6}>
            <Card bordered={false}>
              <Statistic
                title="总客户数"
                value={chartData.keyMetrics.totalCustomers}
                valueStyle={{ color: '#722ed1' }}
                prefix={<UserOutlined />}
              />
              <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', fontSize: 12, color: '#722ed1' }}>
                <ArrowUpOutlined size={12} style={{ marginRight: 4 }} />
                <span>较上期增长 8.7%</span>
              </div>
            </Card>
          </Col>

          <Col xs={24} sm={12} md={8} lg={6}>
            <Card bordered={false}>
              <Statistic
                title="平均订单价值"
                value={chartData.keyMetrics.avgOrderValue}
                precision={2}
                valueStyle={{ color: '#fa8c16' }}
                prefix={<DollarOutlined />}
                suffix="元"
              />
              <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', fontSize: 12, color: '#fa8c16' }}>
                <ArrowDownOutlined size={12} style={{ marginRight: 4 }} />
                <span>较上期下降 2.1%</span>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 销售趋势图表 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col span={24}>
            <Card title="销售趋势" loading={loading}>
              <ResponsiveContainer width="100%" height={300}>
                <LineChart
                  data={chartData.weeklyTrend}
                  margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="day" />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" />
                  <RechartsTooltip formatter={(value, name) => [name === '销售额' ? `¥${value}` : value, name]} />
                  <Legend />
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="sales"
                    name="销售额"
                    stroke="#8884d8"
                    activeDot={{ r: 8 }}
                  />
                  <Line yAxisId="right" type="monotone" dataKey="orders" name="订单数" stroke="#82ca9d" />
                </LineChart>
              </ResponsiveContainer>
            </Card>
          </Col>
        </Row>

        {/* 数据分布图表 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} md={12}>
            <Card title="订单状态分布" loading={loading}>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={chartData.orderStatusDistribution}
                      cx="50%"
                      cy="50%"
                      labelLine={true}
                      label={(props) => {
                        const { name, percent } = props;
                        return `${name}: ${percent != null ? (Number(percent) * 100).toFixed(0) : 0}%`;
                      }}
                      outerRadius={80}
                      fill="#8884d8"
                      dataKey="value"
                    >
                      {chartData.orderStatusDistribution.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color || COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <RechartsTooltip formatter={(value, name) => [`${value} 单`, name]} />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </Card>
          </Col>

          <Col xs={24} md={12}>
            <Card title="支付方式分布" loading={loading}>
              <div style={{ display: 'flex', justifyContent: 'center' }}>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={chartData.paymentMethodDistribution}
                      cx="50%"
                      cy="50%"
                      labelLine={true}
                      label={({ name, percent }) => `${name}: ${(Number(percent) * 100).toFixed(0)}%`}
                      outerRadius={80}
                      fill="#82ca9d"
                      dataKey="value"
                    >
                      {chartData.paymentMethodDistribution.map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={entry.color || COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <RechartsTooltip formatter={(value, name) => [`${value} 单`, name]} />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 销售额和订单数按日期统计 */}
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Card title="销售额和订单数统计" loading={loading}>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart
                  data={chartData.salesByDate}
                  margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" />
                  <RechartsTooltip formatter={(value, name) => [name === '销售额' ? `¥${value}` : value, name]} />
                  <Legend />
                  <YAxis
                    yAxisId="left"
                    tickFormatter={(value) =>
                      typeof value === 'number' ? (value >= 10000 ? `${(value / 10000).toFixed(1)}万` : value) : value
                    }
                  />
                  <Bar yAxisId="right" dataKey="orders" name="订单数" fill="#82ca9d" />
                </BarChart>
              </ResponsiveContainer>
            </Card>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default OrderAggregate;